/*
 * Name: Profile
 * Author: Sam Oakley
 * Date: 4/4/2010
 * Version Number: 1.1
 * Description: Allows users to enter their details and save on device
 * for one click signup. Basically a big form that stores in DB.
 * Changes History: 
 * 1.0 Created class
 * 1.1 Added address fields
 */
package com.blork.rag;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;



public class Profile extends Activity {
	private int dYear;
    private int dMonth;
    private int dDay;
    private EditText firstName;
    private EditText lastName;
    private EditText email;
    private EditText mobile;
    private EditText ucard;
    private EditText dob;
    private EditText justGiving;
    private EditText address1;
    private EditText address2;
    private EditText city;
    private EditText postcode;
    private EditText homephone;
    private String uni;
    private String gender;
    private RadioButton male;
    private RadioButton female;
    
    private EditText passportNo;
    
    private RadioButton xs_h;
    private RadioButton s_h;    
    private RadioButton m_h;   
    private RadioButton l_h;   
    private RadioButton xl_h;   
    private RadioButton xxl_h;  
    
    private RadioButton xs_t;
    private RadioButton s_t;    
    private RadioButton m_t;   
    private RadioButton l_t;   
    private RadioButton xl_t;   
    private RadioButton xxl_t;  
    
    private String hoodySize;
    private String tshirtSize;
    
    private EditText docName;
    private EditText docSurgery;
    private EditText docAddress1;
    private EditText docAddress2;
    private EditText docCity;
    private EditText docPostcode;
    private EditText docPhone;
    private EditText docConditions;
    
    private EditText emName;
    private EditText emRelationship;
    private EditText emAddress1;
    private EditText emAddress2;
    private EditText emCity;
    private EditText emPostcode;
    private EditText emPhone;
    
    private int mode = 0;
    
    private UserData user;
     
    
    /** Called when the activity is first created. */ 
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);        
        
        firstName = (EditText) findViewById(R.id.first_name);
        
        lastName = (EditText) findViewById(R.id.last_name);
        
        email = (EditText) findViewById(R.id.email);
        email.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        
        mobile = (EditText) findViewById(R.id.mobile);
        mobile.setInputType(InputType.TYPE_CLASS_PHONE);
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);        
        mobile.setText(tm.getLine1Number());
        
        ucard = (EditText) findViewById(R.id.ucard);
        ucard.setInputType(InputType.TYPE_CLASS_NUMBER);
        
        justGiving = (EditText) findViewById(R.id.just_giving);
        
        address1 = (EditText) findViewById(R.id.address_ln1);
        address1.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
        
        address2 = (EditText) findViewById(R.id.address_ln2);
        address2.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
        
        city = (EditText) findViewById(R.id.city);
        
        postcode = (EditText) findViewById(R.id.postcode);
        
        homephone = (EditText) findViewById(R.id.homephone);
        homephone.setInputType(InputType.TYPE_CLASS_PHONE);
        
        dob = (EditText) findViewById(R.id.dob);   
        dob.setInputType(InputType.TYPE_NULL); 
        dob.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) {
            	showDialog(0); //Date Dialog
            }
        });   
        
        final Calendar c = Calendar.getInstance();
        dYear = c.get(Calendar.YEAR);
        dMonth = c.get(Calendar.MONTH);
        dDay = c.get(Calendar.DAY_OF_MONTH);       
        
        
        male = (RadioButton) findViewById(R.id.male);
        female = (RadioButton) findViewById(R.id.female);        
 
        
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.uni_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
        
        
        passportNo = (EditText) findViewById(R.id.passport_no);
        
        xs_h = (RadioButton) findViewById(R.id.XS_h);
        s_h = (RadioButton) findViewById(R.id.S_h);    
        m_h = (RadioButton) findViewById(R.id.M_h);   
        l_h = (RadioButton) findViewById(R.id.L_h);   
        xl_h = (RadioButton) findViewById(R.id.XL_h);   
        xxl_h = (RadioButton) findViewById(R.id.XXL_h);    

        xs_t = (RadioButton) findViewById(R.id.XS_t);
        s_t = (RadioButton) findViewById(R.id.S_t);    
        m_t = (RadioButton) findViewById(R.id.M_t);   
        l_t = (RadioButton) findViewById(R.id.L_t);   
        xl_t = (RadioButton) findViewById(R.id.XL_t);   
        xxl_t = (RadioButton) findViewById(R.id.XXL_t);    
        
        docName = (EditText) findViewById(R.id.doc_name);
        docSurgery= (EditText) findViewById(R.id.doc_surgery);
        docAddress1= (EditText) findViewById(R.id.doc_address_ln1);
        docAddress2= (EditText) findViewById(R.id.doc_address_ln2);
        docCity= (EditText) findViewById(R.id.doc_city);
        docPostcode= (EditText) findViewById(R.id.doc_postcode);
        docPhone= (EditText) findViewById(R.id.doc_phone);
        docConditions= (EditText) findViewById(R.id.doc_conditions);
               
        emName = (EditText) findViewById(R.id.em_name);
        emRelationship = (EditText) findViewById(R.id.em_relationship);
        emAddress1 = (EditText) findViewById(R.id.em_address_ln1);
        emAddress2 = (EditText) findViewById(R.id.em_address_ln1);
        emCity = (EditText) findViewById(R.id.em_city);
        emPostcode = (EditText) findViewById(R.id.em_postcode);
        emPhone = (EditText) findViewById(R.id.em_phone);
        
        
        final Button submit = (Button) findViewById(R.id.save);      
        submit.setOnClickListener(new View.OnClickListener() { 
        	/*
        	 * Name: onClick.
        	 * Description: Validates user's data, saves it.
        	 * If they got here by trying to sign up to an event,
        	 * send them back to the event details page.
        	 * Parameters: The clicked View v.
        	 */
            public void onClick(View v) {
				if(validateInput() == true){
					try {
						addDetails();
					} catch (Exception e) {
						Log.e("adding", e.toString());
					}
					Toast.makeText(getApplicationContext(), "Saved.",
		     	              Toast.LENGTH_LONG).show();
				   
					String title = null;
					try {
						Bundle extras = getIntent().getExtras(); 
						title = extras.getString("title");
					} catch (Exception e) {
						e.printStackTrace();
					}
				    
					if (title == null) {
						Intent a = new Intent(Profile.this, Rag.class);
						startActivity(a);
					}else{
						Intent a = new Intent(Profile.this, Event.class);
						a.putExtra("title", (String)title);
						startActivity(a);
					}
				}
            }
        }); 
        
	    user = new UserData(this);
		SQLiteDatabase db = user.getReadableDatabase();
			Cursor details = db.query("user", new String[] {"_id, first_name, last_name, dob, just_giving_url, gender, " +
					"mobile, email, uni, ucard, address1, address2, city, postcode, homephone, passport_no, hoody_size, tshirt_size, " +
					"docName, docSurgery, docAddress1, docAddress2, docCity, docPostcode, docPhone, docConditions, emName, emRelationship, emAddress1, emAddress2, emCity, emPostcode, emPhone"}, 
		            "_id=1", null, null, null, null);	
			startManagingCursor(details);

		try {
			if (details.moveToFirst()){
				mode = 1; //set so I can tell if details should be added or updated 
				firstName.setText(details.getString(details.getColumnIndex("first_name")));
				lastName.setText(details.getString(details.getColumnIndex("last_name")));
				dob.setText(details.getString(details.getColumnIndex("dob")));		
				justGiving.setText(details.getString(details.getColumnIndex("just_giving_url")));
				if(details.getString(details.getColumnIndex("gender")).equals("male")){
					male.toggle();
				}else if(details.getString(details.getColumnIndex("gender")).equals("female")){
					female.toggle();
				}				
				mobile.setText(details.getString(details.getColumnIndex("mobile")));		
				email.setText(details.getString(details.getColumnIndex("email")));
				if(details.getString(details.getColumnIndex("uni")).equals("University of Sheffield")){
					spinner.setSelection(0);
				}else if(details.getString(details.getColumnIndex("uni")).equals("Sheffield Hallam University")){
					spinner.setSelection(1);
				}else{
					spinner.setSelection(2);
				}
				ucard.setText(details.getString(details.getColumnIndex("ucard")));
				address1.setText(details.getString(details.getColumnIndex("address1")));
				address2.setText(details.getString(details.getColumnIndex("address2")));
				city.setText(details.getString(details.getColumnIndex("city")));
				postcode.setText(details.getString(details.getColumnIndex("postcode")));
				homephone.setText(details.getString(details.getColumnIndex("homephone")));

				passportNo.setText(details.getString(details.getColumnIndex("passport_no")));				
				
				if(details.getString(details.getColumnIndex("hoody_size")).equals("XS")){
					xs_h.toggle();
				}else if(details.getString(details.getColumnIndex("hoody_size")).equals("S")){
					s_h.toggle();
				}else if(details.getString(details.getColumnIndex("hoody_size")).equals("M")){
					m_h.toggle();
				}else if(details.getString(details.getColumnIndex("hoody_size")).equals("L")){
					l_h.toggle();
				}else if(details.getString(details.getColumnIndex("hoody_size")).equals("XL")){
					xl_h.toggle();
				}else if(details.getString(details.getColumnIndex("hoody_size")).equals("XXL")){
					xxl_h.toggle();
				}

				if(details.getString(details.getColumnIndex("tshirt_size")).equals("XS")){
					xs_t.toggle();
				}else if(details.getString(details.getColumnIndex("tshirt_size")).equals("S")){
					s_t.toggle();
				}else if(details.getString(details.getColumnIndex("tshirt_size")).equals("M")){
					m_t.toggle();
				}else if(details.getString(details.getColumnIndex("tshirt_size")).equals("L")){
					l_t.toggle();
				}else if(details.getString(details.getColumnIndex("tshirt_size")).equals("XL")){
					xl_t.toggle();
				}else if(details.getString(details.getColumnIndex("tshirt_size")).equals("XXL")){
					xxl_t.toggle();
				}

				docName.setText(details.getString(details.getColumnIndex("docName")));
				docSurgery.setText(details.getString(details.getColumnIndex("docSurgery")));
				docAddress1.setText(details.getString(details.getColumnIndex("docAddress1")));
				docAddress2.setText(details.getString(details.getColumnIndex("docAddress2")));
				docCity.setText(details.getString(details.getColumnIndex("docCity")));
				docPostcode.setText(details.getString(details.getColumnIndex("docPostcode")));
				docPhone.setText(details.getString(details.getColumnIndex("docPhone")));
				docConditions.setText(details.getString(details.getColumnIndex("docConditions")));
				emName.setText(details.getString(details.getColumnIndex("emName")));
				emRelationship.setText(details.getString(details.getColumnIndex("emRelationship")));
				emAddress1.setText(details.getString(details.getColumnIndex("emAddress1")));
				emAddress2.setText(details.getString(details.getColumnIndex("emAddress2")));
				emCity.setText(details.getString(details.getColumnIndex("emCity")));
				emPostcode.setText(details.getString(details.getColumnIndex("emPostcode")));
				emPhone.setText(details.getString(details.getColumnIndex("emPhone")));
	
			}
		} catch (Exception e) {
			Log.e("Failed getting user from db", e.toString());
		}	
    }
	
	public class MyOnItemSelectedListener implements OnItemSelectedListener {
	    public void onItemSelected(AdapterView<?> parent,
	        View view, int pos, long id) {
	        uni = parent.getItemAtPosition(pos).toString();
	    }

	    @SuppressWarnings("unchecked")
		public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}
	
	@Override 
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case 0:
	        return new DatePickerDialog(this,
	                    dateSetListener,
	                    dYear, dMonth, dDay);
	    }
	    return null;
	}
	
    // updates the date we display in the TextView
    private void updateDisplay() {
        dob.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(dDay).append("/")
                    .append(dMonth + 1).append("/")
                    .append(dYear));
    }
    
    private DatePickerDialog.OnDateSetListener dateSetListener =
        new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                dYear = year;
                dMonth = monthOfYear;
                dDay = dayOfMonth;
                updateDisplay(); 
            }

        };
        
    /*
     * Name: validateInput.
     * Description: Checks all user input. Those that can be are validated with regular expressions.
     * Displays alert to user telling them what to fix.
     * Remember, string comparisons in Java are stupid!
     * Output: True if valid, else False.
     */    
    private boolean validateInput(){
    	ArrayList<String> errors = new ArrayList<String>();

		if(firstName.getText().toString().length() == 0){
			errors.add("Please enter your first name.");
		}
		
		if(lastName.getText().toString().length() == 0){
			errors.add("Please enter your first name.");
		}  
		
		if(dob.getText().toString().length() == 0){
			errors.add("Please enter your date of birth.");
		} 
		
		if(address1.getText().toString().length() == 0){
			errors.add("Please enter your address.");
		} 
		if(city.getText().toString().length() == 0){
			errors.add("Please enter a city.");
		} 	
		
		if(!postcode.getText().toString().toUpperCase().matches("^(GIR ?0AA|(?:[A-PR-UWYZ](?:\\d|\\d{2}|[A-HK-Y]\\d|[A-HK-Y]\\d\\d|\\d[A-HJKSTUW]|[A-HK-Y]\\d[ABEHMNPRV-Y])) ?\\d[ABD-HJLNP-UW-Z]{2})$")){
			errors.add("Please enter a valid postcode.");
		} 
		
		if(!dob.getText().toString().matches("^\\d{1,2}\\/\\d{1,2}\\/\\d{4}$")){
			errors.add("Please enter a valid date of birth, DD/MM/YYYY.");
		} 	
		
    	if(male.isChecked() == true){
    		gender = "male";
		}else if(female.isChecked() == true){
    		gender = "female";
    	}else{
    		errors.add("Please select your Gender.");
    	}
    	
		if(!mobile.getText().toString().matches("^(\\+44\\s?7\\d{3}|\\(?07\\d{3}\\)?)\\s?\\d{3}\\s?\\d{3}$")){
			errors.add("Please enter a valid mobile phone number.");
		} 
		
		if(!email.getText().toString().matches("^([a-zA-Z0-9]+([\\.+_-][a-zA-Z0-9]+)*)@(([a-zA-Z0-9]+((\\.|[-]{1,2})[a-zA-Z0-9]+)*)\\.[a-zA-Z]{2,6})$")){
			errors.add("Please enter a valid email address.");
		} 	
		
		if(!homephone.getText().toString().equals("") && !homephone.getText().toString().matches("(\\s*\\(?0\\d{4}\\)?\\s*\\d{6}\\s*)|(\\s*\\(?0\\d{3}\\)?\\s*\\d{3}\\s*\\d{4}\\s*)")){
			errors.add("Please enter a valid home phone number.");
		}
		
		if(!passportNo.getText().toString().equals("") && !passportNo.getText().toString().matches("^[0-9]{10}GBR[0-9]{7}[U,M,F]{1}[0-9]{9}$")){
			errors.add("Please enter a valid passport number.");
		} 
		
    	if(xs_h.isChecked() == true){
    		hoodySize = "XS";
		}else if(s_h.isChecked() == true){
			hoodySize = "S";
    	}else if(m_h.isChecked() == true){
			hoodySize = "M";
    	}else if(l_h.isChecked() == true){
			hoodySize = "L";
    	}else if(xl_h.isChecked() == true){
			hoodySize = "XL";
    	}else if(xxl_h.isChecked() == true){
			hoodySize = "XXL";
    	}
    	
    	if(xs_t.isChecked() == true){
    		tshirtSize = "XS";
		}else if(s_t.isChecked() == true){
			tshirtSize = "S";
    	}else if(m_t.isChecked() == true){
    		tshirtSize = "M";
    	}else if(l_t.isChecked() == true){
    		tshirtSize = "L";
    	}else if(xl_t.isChecked() == true){
    		tshirtSize = "XL";
    	}else if(xxl_t.isChecked() == true){
    		tshirtSize = "XXL";
    	}
    	
		if(!docPhone.getText().toString().equals("") && !docPhone.getText().toString().matches("(\\s*\\(?0\\d{4}\\)?\\s*\\d{6}\\s*)|(\\s*\\(?0\\d{3}\\)?\\s*\\d{3}\\s*\\d{4}\\s*)")){
			errors.add("Please enter a valid doctor's phone number.");
		}
		if(!docPostcode.getText().toString().equals("") && !docPostcode.getText().toString().toUpperCase().matches("^(GIR ?0AA|(?:[A-PR-UWYZ](?:\\d|\\d{2}|[A-HK-Y]\\d|[A-HK-Y]\\d\\d|\\d[A-HJKSTUW]|[A-HK-Y]\\d[ABEHMNPRV-Y])) ?\\d[ABD-HJLNP-UW-Z]{2})$")){
			errors.add("Please enter a valid doctor's postcode.");
		}
		if(!emPhone.getText().toString().equals("") && !emPhone.getText().toString().matches("(\\s*\\(?0\\d{4}\\)?\\s*\\d{6}\\s*)|(\\s*\\(?0\\d{3}\\)?\\s*\\d{3}\\s*\\d{4}\\s*)")){
			errors.add("Please enter a valid emergency phone number.");
		}
		if(!emPostcode.getText().toString().equals("") && !emPostcode.getText().toString().toUpperCase().matches("^(GIR ?0AA|(?:[A-PR-UWYZ](?:\\d|\\d{2}|[A-HK-Y]\\d|[A-HK-Y]\\d\\d|\\d[A-HJKSTUW]|[A-HK-Y]\\d[ABEHMNPRV-Y])) ?\\d[ABD-HJLNP-UW-Z]{2})$")){
			errors.add("Please enter a valid emergency postcode.");
		}
    	
		if(errors.size()==0){
    		return true;
		}else{
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setTitle("Please check your input.");
			String errorMessage = "";
			for(String error : errors){
				errorMessage = errorMessage + error + "\n";
			}
			dialog.setMessage(errorMessage);
			dialog.show();
    		return false;
    	}
    }
    /*
     * Name: addDetails.
     * Description: Adds/updates the user's details. 
     */   
	private void addDetails(){
		user = new UserData(this);
		//Insert a new record into the Events data source.
		SQLiteDatabase db = user.getWritableDatabase();
		ContentValues values= new ContentValues();
		values.put("first_name", firstName.getText().toString());
		values.put("last_name",lastName.getText().toString());
		values.put("dob", dob.getText().toString());
		values.put("just_giving_url", justGiving.getText().toString());
		values.put("gender", gender);
		values.put("mobile", mobile.getText().toString());
		values.put("email", email.getText().toString());
		values.put("uni", uni);
		values.put("ucard", ucard.getText().toString());
		values.put("address1", address1.getText().toString());
		values.put("address2", address2.getText().toString());
		values.put("city", city.getText().toString());
		values.put("postcode", postcode.getText().toString());
		
		values.put("homephone", homephone.getText().toString());
		
		values.put("passport_no", passportNo.getText().toString());
		values.put("hoody_size", hoodySize);
		values.put("tshirt_size", tshirtSize);
		
		values.put("docName", docName.getText().toString());
		values.put("docSurgery", docSurgery.getText().toString());
		values.put("docAddress1", docAddress1.getText().toString());
		values.put("docAddress2", docAddress2.getText().toString());
		values.put("docCity", docCity.getText().toString());
		values.put("docPostcode", docPostcode.getText().toString());
		values.put("docPhone", docPhone.getText().toString());
		values.put("docConditions", docConditions.getText().toString());
		values.put("emName", emName.getText().toString());
		values.put("emRelationship", emRelationship.getText().toString());
		values.put("emAddress1", emAddress1.getText().toString());
		values.put("emAddress2", emAddress2.getText().toString());
		values.put("emCity", emCity.getText().toString());
		values.put("emPostcode", emPostcode.getText().toString());
		values.put("emPhone", emPhone.getText().toString());
		
		if(mode==0){
			db.insertOrThrow("user", null,values);
		}else{
			db.update("user", values, "_id=1", null);
		}
	}   
}
